<template>
  <div class='page-content'>

    <!-- 工具栏区域 -->
    <table-bar :showTop="false"
               :columns="columns"
               @changeColumn="changeColumn">
      <!-- 条件查询区域 -->
      <div slot="top">
        <el-form :model="queryForm"
                 :rules="queryFormRules"
                 ref="queryFormRef"
                 label-width="70px">

          <el-row :gutter="20">
            <el-col :xs="24"
                    :sm="12"
                    :lg="7">
              <el-form-item label="日期："
                            prop="date">
                <el-date-picker v-model="date"
                                @change="dateChange"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24"
                    :sm="12"
                    :lg="6">
              <el-form-item label="流程名称">
                <el-input v-model="queryForm.processName"
                          placeholder="流程名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24"
                    :sm="12"
                    :lg="6">
              <el-form-item label="流程描述">
                <el-input v-model="queryForm.processDescribe"
                          placeholder="请输入流程描述"></el-input>
              </el-form-item>
            </el-col>

            <el-row :xs="24"
                    :sm="12"
                    :lg="6"
                    style="float: right; margin-right: 10px;">
              <el-button type="primary"
                         @click="query">搜索</el-button>
              <el-button @click="resetForm('queryFormRef')">重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>

      <!-- 左侧按钮 -->
      <div slot="bottom">
        <el-button type="primary"
                   plain
                   @click="showAddDialog">新增流程</el-button>
        <el-button type="danger"
                   plain
                   @click="delByIds">批量删除</el-button>
      </div>

    </table-bar>

    <!-- 表格区域 -->
    <the-table :data="flowList"
               @getDataBySelectBox="handleSelectionChange"
               :showPage="false"
               ref="flowListRef">
      <el-table-column type="selection"
                       width="55" />

      <el-table-column label="序号"
                       type="index"
                       v-if="columns[0].show" />
      <el-table-column label="流程id"
                       prop="processId"
                       v-if="columns[1].show" />
      <el-table-column label="名称"
                       prop="processName"
                       v-if="columns[2].show" />
      <el-table-column label="描述"
                       :show-overflow-tooltip="true"
                       min-width="150px"
                       prop="processDescribe"
                       v-if="columns[3].show" />
      <el-table-column label="创建时间"
                       prop="gmtCreate"
                       v-if="columns[4].show" />

      <el-table-column label="修改时间"
                       prop="gmtModified"
                       v-if="columns[5].show" />
      <el-table-column fixed="right"
                       label="操作"
                       min-width="180px"
                       v-if="columns[6].show">

        <template slot-scope="scope">
          <el-button type="text"
                     icon="el-icon-document"
                     @click="showDetailsDialog(scope.row)">
            详情
          </el-button>
          <el-button type="text"
                     icon="el-icon-edit"
                     @click="showEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button type="text"
                     style="color: #FA6962"
                     icon="el-icon-delete"
                     @click="delById(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>

    <!-- 分页器区域 -->
    <el-pagination layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[1, 5, 10, 15]"
                   :page-size="pageSize"
                   :current-page="pageNum"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   class="page">
    </el-pagination>

    <!-- 新增&修改流程对话框 -->
    <el-dialog :title="isShowAddForm?'新增流程':'修改流程'"
               :visible.sync="addDialog"
               width="50%">
      <el-form ref="addFormRef"
               :model="addForm"
               :rules="addFormRules"
               label-width="100px">

        <el-form-item label="流程名称"
                      prop="processName">
          <el-input v-model="addForm.AddPro.processName"></el-input>
        </el-form-item>
        <el-divider>关联工艺</el-divider>

        <el-steps :active="active"
                  finish-status="success"
                  align-center>
          <el-step title="工艺选取"></el-step>
          <el-step title="工艺排序"></el-step>
        </el-steps>
        <!-- 工艺列表 -->
        <the-table v-show="active === 0"
                   height="250"
                   :data="technologyList"
                   :showPage="false"
                   @getDataBySelectBox="handlesortListChange"
                   ref="table">
          <el-table-column type="selection"
                           width="55"></el-table-column>

          <el-table-column label="工艺名称"
                           prop="echnologyName" />
          <el-table-column label="工艺描述"
                           :show-overflow-tooltip="true"
                           prop="technologyDescribe" />

        </the-table>
        <!-- 工艺排序 -->
        <sort-table v-show="active === 1"
                    :data="sortTechnologyList"
                    @change="handleSortTableChange"
                    height="250">
          <el-table-column label="工艺名称"
                           prop="echnologyName" />
          <el-table-column label="工艺描述"
                           prop="technologyDescribe" />
        </sort-table>

      </el-form> <span slot="footer"
            class="dialog-footer">
        <el-button :disabled="isSelect"
                   @click="next">{{active===0?'下一步':'上一步'}}
        </el-button>
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="()=>isShowAddForm?add():update()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 流程详情对话框 -->
    <el-dialog title="屠宰流水线"
               :visible.sync="detailsDialog"
               width="70%">
      <div>
        <the-table :data="detailsList"
                   :showPage="false">

          <el-table-column label="工序"
                           prop="sort" />
          <el-table-column label="工艺名称"
                           prop="echnologyName" />
          <!--       <el-table-column label="描述"
                           min-width="150px">
            <template slot-scope="scope">
              <el-popover v-if="scope.row.technologyDescribe.length>12"
                          placement="top"
                          width="200"
                          trigger="hover"
                          :content="scope.row.technologyDescribe">
                <div slot="reference">{{shortDescribe(scope.row.technologyDescribe)}}
                </div>
              </el-popover>
              <div v-else>{{scope.row.technologyDescribe}}</div>
            </template>
          </el-table-column> -->
          <el-table-column label="创建时间"
                           prop="gmtCreate" />

          <el-table-column label="修改时间"
                           prop="gmtModified" />
        </the-table>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="detailsDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="detailsDialog = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import { changeColumn, pagination, dialogClose, multipleSelection, queryForm } from '@/api/mixin'
import { dateShorter } from '@/utils/utils'
export default {
  name: "FlowManage",
  meta: {
    title: "屠宰流程管理",
  },
  mixins: [changeColumn, pagination, dialogClose, queryForm, multipleSelection],
  data () {
    return {
      // 流程列表
      flowList: [],
      detailsList: [],
      columns: [
        { name: "序号", show: true },
        { name: "id", show: false },
        { name: "名称", show: true },
        { name: "描述", show: true },
        { name: "创建时间", show: true },
        { name: "修改时间", show: true },
        { name: "操作", show: true },
      ],
      options: [],
      date: [],
      queryForm: {
        processName: '',//流程名称
        processDescribe: '',//流程描述
        begin: '',
        end: '',
      },
      // 条件查询表单检验规则
      queryFormRules: {
        date: [],
        type: [],
        id: []
      },
      addDialog: false,
      editDialog: false,
      detailsDialog: false,
      addForm: {
        AddPro: {
          shId: '',//屠宰场
          processName: '',
          // shBatch: '',
          // processDescribe:''
          guige: 3
        },
        AddSortTec: [
          // {
          //   sort: 1,
          //   Tec: '活禽验收'
          // }
        ]
      },
      //工艺列表
      technologyList: [],
      // 排序的工艺列表
      sortTechnologyList: [
        {
          sort: 0,
          technologyName: 'abc', technologyDescribe: 'abc'
        },
        {
          sort: 3,
          technologyName: 'ddd', technologyDescribe: 'ddd'
        },
        {
          sort: 2,
          technologyName: 'ggg', technologyDescribe: 'ggg'
        },
      ],
      options: [],
      active: 0,
      //按钮禁用
      isSelect: true,
      addFormRules: {
        processName: [{ required: true, message: '请输入流程名称', trigger: 'blur' }, { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }],
        processDescribe: [{ required: true, message: '请输入流程描述', trigger: 'blur' }, { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }],
      },
      /* editForm: {
        guige: 0,//写死
        shId: 0,//所属屠宰场 id
        processDescribe: '',
        processName: ''
      }, */
      processId: '',//暂存
      isShowAddForm: true
    }
  },
  computed: {
    select_shId () {
      return this.$store.state.Usersetting.SlaughterInfo.shId
    }
  },
  methods: {
    getList () {
      this.getFlowList()
    },
    shortDescribe (val) {
      if (val.length)
        return val.length < 12 ? val : val.slice(0, 12) + '..'
      return ''
    },
    // 监听日期选择器变化
    dateChange (val) {
      // 没有选中val = null
      // console.log('[ val ] >', val)
      if (!val) {
        this.queryForm.begin = ''
        this.queryForm.end = ''
        return this.getList()
      }
      this.queryForm.begin = val[0]
      this.queryForm.end = val[1]

    },
    //分页获取列表
    async getFlowList () {
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-process/getPageTO/${this.pageNum}/${this.pageSize}`)

      if (res.statusCode !== 20000) return this.$message.error('获取流程列表失败')

      //保存
      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      this.flowList = res.data.records
      this.total = res.data.total

    },
    // 条件查询
    async query () {
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-process/pageTs/${this.pageNum}/${this.pageSize}`, { params: this.queryForm })
      if (res.statusCode !== 20000) return this.$message.error('查询失败')

      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      this.flowList = res.data.records
      this.total = res.data.total
    },
    //分页器变化监听
    getList () {
      this.getFlowList()
    },

    /* 删除 */
    delById ({ processId }) {
      this.delById_Pigeon('/pigeon/t-slaughterhouse-type/deleteTsById/', processId)
    },
    delByIds () {
      this.delByIds_Pigeon('/pigeon/t-slaughterhouse-process/deleteByIds/', 'processId')
    },
    /* 删除 */

    /* 编辑 */
    async showEditDialog ({ processId }) {
      //保存id
      this.processId = processId
      //获取最新的记录
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-process/getLaughterById/${processId}`)
      if (res.statusCode !== 20000) return this.$message.error('获取最新的流程记录失败')


      //获取工艺列表
      this.getTechnologyList()


      //处理获取的记录的工艺
      let stringTechnologyList = []
      if (res.data.processDescribe.length) {
        stringTechnologyList = res.data.processDescribe.split('->')
      }
      // console.log(stringTechnologyList);

      //在所有工艺中，标记流程记录原有的
      const rowTechnologyList = []
      stringTechnologyList.forEach(x => {
        const target = this.technologyList.find(item => item.echnologyName === x)
        rowTechnologyList.push(target)
      })

      this.toggleSelection(rowTechnologyList)

      //保存
      this.addForm.AddPro.processName = res.data.processName


      // 显示
      this.isShowAddForm = false
      this.addDialog = true
    },
    update () {
      // 表单验证
      this.$refs.editFormRef.validate(async flag => {
        if (!flag)
          return this.$message.error('请正确填写表单')
        // 发送请求
        const { data: res } = await this.$http.put(`/pigeon/t-slaughterhouse-process/updateTs/${this.processId}`, this.editForm)
        if (res.statusCode !== 20000) return this.$message.error('修改失败')


        // 关闭
        this.editDialog = false
        this.$message.success('修改成功')

        //刷选列表
        this.getList()

      })





    },


    /* 编辑 */

    /* 新增 */
    async showAddDialog () {
      this.addForm.AddPro.guige = 3 // 写死？
      this.addForm.AddPro.shId = this.select_shId


      // 获取工艺列表
      this.getTechnologyList()

      this.isShowAddForm = true
      this.addDialog = true
    },
    async add () {
      this.addForm.AddSortTec = []
      //保存工序
      this.sortTechnologyList.forEach((item, index) => {
        this.addForm.AddSortTec.push({
          sort: index,
          Tec: item.echnologyName
        })
      })
      this.$refs.addFormRef.validate(async flag => {
        // if (!flag)
        //   return this.$message.error('请正确填写表单')
        const { data: res } = await this.$http.post(`/pigeon/t-slaughterhouse-process/saveTs`, this.addForm)
        if (res.statusCode !== 20000) return this.$message.error('添加失败')

        this.$message.success('添加成功')
        this.getList()
        this.addDialog = false
      })

    },
    // 工艺数据多选
    handlesortListChange (val) {
      if (val.length > 0) {
        this.sortTechnologyList = val
        this.isSelect = false
      }
      else {
        this.isSelect = true

      }
    },
    /* 新增 */

    /* 详情 */
    async showDetailsDialog ({ processId }) {
      const { data: res } = await this.$http.post(`/pigeon/t-slaughterhouse-pro-tec/getTechnology/${processId}/1/50`)
      if (res.statusCode !== 20000) return this.$message.error('获取详情失败')

      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      this.detailsList = res.data.records

      // console.log(this.detailsList);
      this.detailsDialog = true
    },

    /* 排序 */
    handleSortTableChange (val) {
      // 保存排序后的数组
      this.sortTechnologyList = val

      val.map(item => console.log(item.technologyName))
    },
    next () {
      if (this.active === 0) {
        // 下一步
        this.active = 1
      } else {
        // 返回上一步
        this.active = 0
        // 禁用按钮,需要重选数据解开
        // this.isSelect = true

      }
    },
    dialogClose () {
      // 重置设置
      this.active = 0
      // this.technologyList = []
      this.sortTechnologyList = []
    },
    async getTechnologyList () {
      const { data: res2 } = await this.$http.get(`/pigeon/t-slaughterhouse-technology/pageTs/1/51`)
      if (res2.statusCode !== 20000) return this.$message.error('获取工艺列表失败')

      this.technologyList = res2.data.records
    },
    //多选框勾选
    toggleSelection (rows) {
      /* console.log(this.$refs.mytable, ' this.$refs.mytable');
      if (rows) {
        rows.forEach(row => {
          this.$refs.mytable.toggleRowSelection(row);
        });
      } else {
        this.$refs.mytable.clearSelection();
      }
      console.log(11); */
    }

  },
  created () {
    this.getFlowList()
  }
}
</script>

<style scoped>
.page {
  margin-top: 6px;
  text-align: center;
}
.el-date-editor--daterange.el-input,
.el-date-editor--daterange.el-input__inner,
.el-date-editor--timerange.el-input,
.el-date-editor--timerange.el-input__inner {
  width: 100%;
}
.el-steps {
  margin: 20px 0;
}
.el-step__title {
  font-size: 14px;
}
</style>